package com.aspire.nm.component.cmppserver.filter.keepAlive;

import javax.annotation.Resource;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
import org.springframework.stereotype.Service;

import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppActiveTestPacket;
import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppActiveTestRespPacket;
import com.aspire.nm.component.cmppserver.runTime.Connection;
import com.aspire.nm.component.cmppserver.runTime.SysRunTimeService;
import com.aspire.nm.component.cmppserver.runTime.UserRunTime;
import com.aspire.nm.component.cmppserver.util.LogService;
import com.aspire.nm.component.commonUtil.seq.SequenceGenerator;

@Service
public class KeepAliveMessage implements KeepAliveMessageFactory {

	private SequenceGenerator seq = SequenceGenerator.getSequenceGenerator(1,Integer.MAX_VALUE);


	
	@Resource
	private LogService logService;
	@Resource
	private SysRunTimeService sysRunTimeService;
	
	@Override
	public boolean isRequest(IoSession session, Object message) {
		if(message instanceof CmppActiveTestPacket){
			return true;
		}
		return false;
	}

	@Override
	public boolean isResponse(IoSession session, Object message) {
		if(message instanceof CmppActiveTestRespPacket){
			if(((CmppActiveTestRespPacket)message).bizParams != null){
				setActiveLastTime(session);
				//主动发起的心跳请求对应的应答
				logService.activeToResp(session, (CmppActiveTestRespPacket)message);
			}
			return true;
		}
		return false;
	}

	@Override
	public Object getRequest(IoSession session) {
		CmppActiveTestPacket cmppActiveTestPacket = new CmppActiveTestPacket();
		cmppActiveTestPacket.setSequenceId(seq.nextInt());
		logService.activeTo(session, cmppActiveTestPacket);
		
		return cmppActiveTestPacket;
	}

	@Override
	public Object getResponse(IoSession session, Object request) {
		setActiveLastTime(session);
		
		logService.activeFrom(session, ((CmppActiveTestPacket)request));
		
		CmppActiveTestRespPacket cmppActiveTestRespPacket = new CmppActiveTestRespPacket();
		cmppActiveTestRespPacket.setSequenceId(((CmppActiveTestPacket)request).getSequenceId());
		cmppActiveTestRespPacket.setReserved((byte) 0);
		
		logService.activeFromResp(session, cmppActiveTestRespPacket);
		return cmppActiveTestRespPacket;
	}

	
	private void setActiveLastTime(IoSession session){
		UserRunTime userRunTime = sysRunTimeService.getUserRunTime(session);
		if(userRunTime != null){
			Connection connection = userRunTime.getConnection(session);
			if(connection != null){
				connection.setActiveLastTime();
			}
		}
	}
}
